package com.wmapp.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
 * 验证用户是否非法进入
 * @author dengl
 *
 */
public class AuthorizationFilter implements Filter {
	private String ignoreURL="";
	
	public void init(FilterConfig filterConfig) throws ServletException {
		String paramIgonreURL = filterConfig.getInitParameter("ignoreURL");
		if(StringUtils.hasText(paramIgonreURL))
			this.ignoreURL =paramIgonreURL;
	}

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
			throw new ServletException("AuthorizationFilter just supports HTTP requests");
		}
		
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		
		if(!isIgnoreURL(httpServletRequest)&&!isLogin(httpServletRequest)){//session is expired or illegal access
			if(httpServletRequest.getHeader("X-Requested-With")!=null){//what if ajax request
				httpServletResponse.getWriter().write("__expired__");
			}else{
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/index.jsp");
			}
			return;//不走后面的过滤器了
		}
		
		filterChain.doFilter(request, response);
	}
	/**
	 * 判断是否已登录
	 * @param request
	 * @return true 已登录 false 未登录
	 */
	private boolean isLogin(HttpServletRequest request){
		boolean res = true;
		if(WebUtils.getSessionAttribute(request, "loginInfo")==null){
			res=false;
		}
		return res;
	}
	/**
	 * 判断URI是否在忽略的范围内
	 * @param request
	 * @return true 忽略，不进行权限控制 false 在权限控制范围内
	 */
	private boolean isIgnoreURL(HttpServletRequest request){
		boolean res=false;
		String url=request.getRequestURI();
		String contextPath=request.getContextPath();
		url=url.substring(contextPath.length());
		String[] urls=this.ignoreURL.split(",");
		
		for (int i = 0; i < urls.length; i++) {
			if(url.trim().equals(urls[i].trim())){
				res=true;
				break;
			}
		}
		
		return res;
	}
}
